package com.mutual.assistance.task.utils;

import com.mutual.assistance.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import toolgood.words.StringSearch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenyuxin
 * @version 1.0
 * @description 敏感词过滤工具类
 * @date 2023/5/4 12:56
 */
@Slf4j
public class SensitiveWordUtils {


    private final static List<String> list = new ArrayList<>(20000);

    static {
        try {
            InputStream inputStream = SensitiveWordUtils.class.getResourceAsStream("/static/SensitiveWordList.txt");
            if (inputStream != null) {
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                String line = null;
                while ((line = br.readLine()) != null) {
                    log.error("敏感词：{}", line);
                    list.add(line);
                }
            }
        } catch (IOException e) {
            throw new BizException(e);
        }
    }


    /**
     * 判断是否存在敏感词
     *
     * @param txt 文本
     */
    public static Boolean judgeSensitivityWord(String txt) {
        StringSearch iwords = new StringSearch();
        iwords.SetKeywords(list);
        return iwords.ContainsAny(txt);
    }

    /**
     * 敏感词过滤用*替代
     *
     * @param txt     内容
     * @param replace 敏感词替代字符 '*'
     */
    public static String filterSensitivityWord(String txt, char replace) {
        StringSearch iwords = new StringSearch();
        iwords.SetKeywords(list);
        return iwords.Replace(txt, replace);
    }
}
